using UnityEngine;
using System.Collections;

[AddComponentMenu("TagMachine/Entity/Player")]
public class PlayerEntity : MonoBehaviour 
{
	public float SwitchTime 				= 1.0f;
	private float m_CurrentSwitchTime		= 0.0f;
	public bool IsSwitching 				{ get { return m_CurrentSwitchTime > 0.0f; } }

	public bool IsWolf 						{ get { return WolfComp.gameObject.activeInHierarchy; } }

	public Wolf WolfComp 					{ get; private set; }
	public Fugitive FugitiveComp 			{ get; private set; }

	private GameObject m_ToSwitchOff		= null;

	void Awake()
	{
		WolfComp 		= transform.Find( "Wolf" ).GetComponent< Wolf >();
		FugitiveComp 	= transform.Find( "Fugitive" ).GetComponent< Fugitive >();
	}

	void Start()
	{
		Reset();

		enabled 		= false;		
	}

	void Update()
	{
		if ( IsSwitching )
		{
			m_CurrentSwitchTime	-= Time.deltaTime;

			if ( m_ToSwitchOff != null &&
				m_CurrentSwitchTime < SwitchTime * 0.5f )
			{
				if ( m_ToSwitchOff == WolfComp.gameObject )
				{
					SwitchToFugitive();
				}
				else
				{
					SwitchToWolf();
				}

				m_ToSwitchOff 	= null;
			}
		}
		else
		{
			enabled = false;
		}
	}

	public void Switch()
	{
		m_CurrentSwitchTime = SwitchTime;
		if ( WolfComp.gameObject.activeInHierarchy )
		{
			m_ToSwitchOff 	= WolfComp.gameObject;
		}
		else
		{
			m_ToSwitchOff 	= FugitiveComp.gameObject;
		}

		enabled = true;
	}

	void OnTriggerEnter( Collider _Other ) 
	{
		if ( IsWolf && _Other.transform.parent != null )
		{
			PlayerEntity OtherPlayerComp = _Other.transform.parent.GetComponent< PlayerEntity >();

			if ( OtherPlayerComp != null &&
				IsWolf != OtherPlayerComp.IsWolf &&
				!IsSwitching && !OtherPlayerComp.IsSwitching &&
			    !OtherPlayerComp.FugitiveComp.IsSafe ) 
			{
				GameModeClassic.Instance.SwitchWolf( OtherPlayerComp );
			}
		}
	}

	public void Reset()
	{
		GetComponent< MovingEntity >().enabled 	= false;
		if ( WolfComp != null )
		{
			WolfComp.gameObject.SetActive( false );
		}
		if ( FugitiveComp != null )
		{
			FugitiveComp.gameObject.SetActive( true );
		}
	}

	public void SwitchToWolf()
	{
		FugitiveComp.gameObject.SetActive( false );
		if ( WolfComp != null )
		{
			WolfComp.Activate();
			gameObject.layer = WolfComp.gameObject.layer;
		}
	}

	public void SwitchToFugitive()
	{
		WolfComp.gameObject.SetActive( false );
		if ( FugitiveComp != null )
		{
			FugitiveComp.Activate();
			gameObject.layer = FugitiveComp.gameObject.layer;
		}
	}
}